<template>
	<div>
		<el-dialog :title="title" :visible.sync="dialogVisible" width="600px" @closed="resetForm('form')" :close-on-click-modal="false">
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="名称" prop="name">
					<el-input v-model="form.name"></el-input>
				</el-form-item>
				<el-form-item label="分类类型" prop="type">
					<el-select style="width: 100%" v-model="form.type" filterable placeholder="请选择分类类型">
						<el-option v-for="(v, i) in courseArr" :key="i" :label="v.msg" :value="v.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="排序" prop="sort">
					<el-input-number v-model="form.sort" :min="1" :max="1000" size="medium" label="排序"></el-input-number>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="custom" v-preventReClick @click="submitForm('form')">提 交</el-button>
				<el-button @click="dialogVisible = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import { tbLabelAdd, tbLabelUpdate } from '@/api/admin/system/label';
export default {
	data() {
		return {
			title: '新增',
			dialogVisible: false,
			addOrEdit: true,
			courseType: '',
			form: {
				type: '',
				name: '',
				sort: 10,
				labelType: 1
			},
			rules: {
				name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
				type: [{ required: true, message: '请选择分类类型', trigger: 'blur' }]
			}
		};
	},
	props: ['courseArr'],
	watch: {
		$route() {
			this.form.labelType = this.$route.meta.labelType;
		}
	},
	mounted() {
		this.courseType = this.courseArr[0].value;
		this.$bus.$on('changeType', this.changeType);
		this.$bus.$on('showDialogLabelAdd', this.init);
	},
	beforeDestroy() {
		this.$bus.$off(['showDialogLabelAdd', 'changeType']);
	},
	methods: {
		changeType(v) {
			this.courseType = v;
		},
		init(row) {
			if (row) {
				this.form = { ...this.form, ...row };
				this.$set(this.form, 'id', row.id);
			} else {
				this.form = this.$options.data().form;
				this.form.type = this.courseType;
				this.$delete(this.form, 'id');
			}
			this.title = row ? '编辑' : '新增';
			this.dialogVisible = true;
		},
		submitForm(form) {
			this.form.labelType = this.$route.meta.labelType;
			this.$refs[form].validate((valid) => {
				if (valid) {
					this.title == '新增' ? this.add() : this.edit();
				}
			});
		},
		//新增
		add() {
			tbLabelAdd(this.form).then((res) => {
				this.done();
			});
		},
		//编辑
		edit() {
			tbLabelUpdate(this.form).then((res) => {
				this.done();
			});
		},
		done() {
			this.dialogVisible = false;
			this.$bus.$emit('refreshLabelList');
			this.$message({
				message: '操作成功',
				type: 'success'
			});
		},
		//重置表单
		resetForm(form) {
			this.$refs[form].resetFields();
		}
	}
};
</script>
